<template>
    <el-upload ref="upload"
               accept=".png,.jpg,.mp4"
               :action="url"
               :headers="headers"
               :disabled="btn.disabled"
               :before-upload="beforeUpload"
               :on-success="success">
        <el-button type="primary" :loading="btn.disabled">
            <span>{{btn.text}}</span>
        </el-button>
    </el-upload>
</template>
<script>
    export default {
        data() {
            return {
                btn: {
                    text: '选择文件',
                    disabled: false,
                },
                headers: {'Authorize': window.localStorage.getItem('ak')},
                url: "/a/upload/local",
                type: '',
            }
        },
        props: {
            insert: {
                type: Function,
            },
        },
        methods: {
            // 文件上传前
            beforeUpload(file) {
                let size = 50, type = '视频';
                if (file.type == "video/mp4") {
                    this.type = 'video';
                } else {
                    size = 2;
                    this.type = 'image';
                    type = '图片'
                }
                if (file.size > size * 1048576) {
                    this.$message.warning(`${type}文件不能超过 ${size}M`);
                    return false;
                }
                this.btn = {
                    text: '文件上传中',
                    disabled: true,
                };
            },
            // 上传成功
            success(res, file) {
                this.btn = {
                    text: '选择文件',
                    disabled: false,
                };
                if (res.code != 1) {
                    this.$message.error(res.msg);
                } else {
                    this.insert({
                        src: res.data.url,
                        type: this.type
                    });
                }
                this.$emit('close')
            },
        },
    }
</script>
<style>

</style>
